package com.edu.framework.websocket.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.assemble.message.MessageAssemble;
import com.edu.framework.websocket.assemble.message.TriggerMsgEngine;
import com.edu.framework.websocket.message.base.Message;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.canteen.CanteenCntRequest;
import com.edu.framework.websocket.message.canteen.CanteenCntVO;
import com.edu.system.domain.TCanteen;
import com.edu.system.domain.dto.CanteenCntDTO;
import com.edu.system.service.ITCanteenService;
import com.edu.system.service.ITChargeRecordService;
import com.edu.system.service.ITExamMissService;
import com.edu.system.service.ITExamSeatService;
import com.edu.system.service.ITExaminationService;
import com.edu.system.service.ITTerminalService;
import java.io.IOException;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @program: xxxx
 * @description:
 * @author: zlh
 * @create: 2024-01-06 18:20
 **/
@Slf4j
@Component
public class CanteenService implements MessageAssemble {

  @Resource
  private ITExamSeatService itExamSeatService;
  @Resource
  private ITExamMissService itExamMissService;
  @Resource
  private ITExaminationService itExaminationService;
  @Resource
  private ITCanteenService itCanteenService;
  @Resource
  private ITTerminalService itTerminalService;
  @Resource
  private ITChargeRecordService itChargeRecordService;



  public Response<CanteenCntVO> getCnt(Long canteenId) {
    if (canteenId == null){
      return null;
    }
    TCanteen tCanteen = itCanteenService.selectTCanteenById(canteenId);
    Integer mealType = this.getMealType(tCanteen);

    Date now = new Date();
    CanteenCntDTO dto = itChargeRecordService.countMealPersonNum(canteenId, DateUtil.beginOfDay(now), DateUtil.endOfDay(now));
    CanteenCntVO vo = CanteenCntVO.builder()
        .morningCnt(dto.getMorningCnt())
        .noonCnt(dto.getNoonCnt())
        .nightCnt(dto.getNightCnt())
        .todayCnt(dto.getTotalCnt())
        .currentCnt(this.getCurrentCnt(dto, mealType))
        .mealType(mealType)
        .morningTimeSlot(tCanteen.getBreakfastTimeRange())
        .noonTimeSlot(tCanteen.getLunchTimeRange())
        .nightTimeSlot(tCanteen.getDinnerTimeRange())
        .morningFee(tCanteen.getBreakfastFee())
        .noonFee(tCanteen.getLunchFee())
        .nightFee(tCanteen.getDinnerFee())
        .build();

    return Response.ok(CanteenCntRequest.TYPE, CanteenCntRequest.RESP_KEY, vo);
  }

  private Integer getCurrentCnt(CanteenCntDTO dto, Integer mealType){

    Integer res = 0;
    if (mealType.equals(1)){
      res = dto.getMorningCnt();
    } else if(mealType.equals(2)){
      res = dto.getNoonCnt();
    } else if(mealType.equals(3)){
      res = dto.getNightCnt();
    }
    return res;
  }

  private Integer getMealType(TCanteen t){

    String[] split = t.getBreakfastTimeRange().split("-");
    String[] split2 = t.getLunchTimeRange().split("-");
    String[] split3 = t.getDinnerTimeRange().split("-");

    Integer title = 1;
    LocalTime now = LocalTime.now();
    if (LocalTime.parse(split[0]).isBefore(now) && LocalTime.parse(split[1]).isAfter(now)){
      title = 1;
    } else if(LocalTime.parse(split2[0]).isBefore(now) && LocalTime.parse(split2[1]).isAfter(now)){
      title = 2;
    } else if(LocalTime.parse(split3[0]).isBefore(now) && LocalTime.parse(split3[1]).isAfter(now)){
      title = 3;
    } else {
      if(LocalTime.parse(split[1]).isBefore(now) && LocalTime.parse(split2[0]).isAfter(now)){
        title = 1;
      } else if (LocalTime.parse(split2[1]).isBefore(now) && LocalTime.parse(split3[0]).isAfter(now)){
        title = 2;
      } else if (LocalTime.parse(split3[1]).isAfter(now)){
        title = 3;
      }
    }
    return title;
  }


  /**
   * 下发
   * @param classIds
   * @throws IOException
   */
  public void pushMsg(List<Long> classIds) {
    Map<String, Long> codeMapId = itTerminalService.codeIdMapByLocationIds(null, "食堂");

    Function<String, Message> fc = code -> {
      log.info("机器:{}", code);
      Response<CanteenCntVO> cnt = getCnt(codeMapId.getOrDefault(code, null));
      log.info("消息:{}", JSONObject.toJSONString(cnt));
      return cnt;
    };
    Consumer<Message> invoke = message -> {};
    try {
      WebSocketHolder.broadcast(fc, invoke);
    } catch (Exception e){
      log.error("主动下发失败 食堂统计", e);
    }

  }

  // 单独定时任务下发
  @Override
  public void buildTrigger(List<Long> firstClassIds) {
//    TriggerMsgEngine.addEveryRun(CanteenService.class.getSimpleName());
  }
}
